
/*
 * AJAX REQUESTS
 */

/*
 * Ensembl DSN request. It gets the reference source for one specie and one built(authority).
 */
YAHOO.dasBrowser.genome.request.makeEnsemblDsnRequest = function(){
	if(YAHOO.dasBrowser.genome.karyotypeStructure.dsn.test){
		var url = YAHOO.dasBrowser.genome.karyotypeStructure.dsn.testUrl;
	} else {
		var url = YAHOO.dasBrowser.genome.karyotypeStructure.proxyUrl + "?" + YAHOO.dasBrowser.proxy.parameters.source + "=" + YAHOO.dasBrowser.genome.karyotypeStructure.referenceUrl + "dsn";
	}
	YAHOO.dasBrowser.genome.karyotypeStructure.dsn.url = url;
    var request = YAHOO.util.Connect.asyncRequest('GET', url, ensemblDsnCallback);
}
/*
 * Entry Points (number of chromosomes) requests.
 */
YAHOO.dasBrowser.genome.request.makeEnsemblEntryPointsRequest = function(){
	if(YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.test){
		var url = YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.testUrl;
	} else {
		var url = YAHOO.dasBrowser.genome.karyotypeStructure.proxyUrl + "?" + YAHOO.dasBrowser.proxy.parameters.source + "=" + YAHOO.dasBrowser.genome.karyotypeStructure.dsn.allDsn[YAHOO.dasBrowser.genome.karyotypeStructure.dsn.selectedDsn.referenceLocation].sourceUrl + "/entry_points";
	}
	YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.url = url;
    var request = YAHOO.util.Connect.asyncRequest('GET', url, ensemblEntryPointsCallback);
	YAHOO.dasBrowser.genome.request.makeSourceStylesheetRequest();
}
/*
 * Stylesheet requests for sources (with styleshet == true)
 */
YAHOO.dasBrowser.genome.request.makeSourceStylesheetRequest = function(){
	var annotationSources = YAHOO.dasBrowser.genome.annotations.sources;
	var stylesheetUrl = '';
	for (var j = 0; j < annotationSources.length; j++) {
		if(annotationSources[j].stylesheet == true){
			stylesheetUrl = '';
			if(annotationSources[j].url.indexOf("features") != -1){
				var newValue_temp = annotationSources[j].url.split("features");
				stylesheetUrl = newValue_temp[0] + "stylesheet";
				var url = YAHOO.dasBrowser.genome.karyotypeStructure.proxyUrl + "?" + YAHOO.dasBrowser.proxy.parameters.source + "=" + stylesheetUrl;
				//console.log(url);
				annotationSources[j].stylesheetData = new Object();
				var request = YAHOO.util.Connect.asyncRequest('GET', url, sourceStylesheetCallback);
				YAHOO.dasBrowser.genome.annotations.mappingRequestIdAnnotationSource[request.tId]=j;
			} else {
				//console.log("failure: source URL incorrect");
			}
		} else {
			//Do not request stylesheet
		}
	}
}

/*
 * Stylesheet request for the Chromosome Bands
 */
YAHOO.dasBrowser.genome.request.makeEnsemblKaryotypeStylesheetRequest = function(){
	YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.stylesheet.url = YAHOO.dasBrowser.genome.karyotypeStructure.proxyUrl + "?" + YAHOO.dasBrowser.proxy.parameters.source + "=" + YAHOO.dasBrowser.genome.karyotypeStructure.dsn.allDsn[YAHOO.dasBrowser.genome.karyotypeStructure.dsn.selectedDsn.karyotypeLocation].sourceUrl + "/stylesheet";
    var request = YAHOO.util.Connect.asyncRequest('GET', YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.stylesheet.url, ensemblKaryotypeStylesheetCallback);
}

/*
 * Chromosome Band request for the Chromosome selected
 */
YAHOO.dasBrowser.genome.request.makeEnsemblChromosomeBandsRequest = function(){
	if (YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.test) {
		var url = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.testUrl;
	} else {
		var chrId = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.selectedChromosome;
		var url = YAHOO.dasBrowser.genome.karyotypeStructure.proxyUrl + "?" + YAHOO.dasBrowser.proxy.parameters.source + "=" + YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomes[chrId].url;
	}
	var request = YAHOO.util.Connect.asyncRequest('GET', url, ensemblChromosomeBandsCallback);
}

/*
 * Chromosome Band request for the rest of the Chromosomes in the karyotype not selected in the chromosome view
 */
YAHOO.dasBrowser.genome.request.makeEnsemblKaryotypeRequest = function(){
	var showChomosome = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.showChromosome;
	var selectedChrId = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.selectedChromosome;
	var isNullKaryotypeFeatures = YAHOO.lang.isNull(YAHOO.dasBrowser.genome.karyotypeStructure.dsn.selectedDsn.karyotypeLocation);
	if(isNullKaryotypeFeatures == false){
		//for (var i in YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomes) {
		var selectedEntryPointsIds = YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.selectedEntryPoints.ids;
		for (var j = 0; j < selectedEntryPointsIds.length; j++) {
			if(selectedEntryPointsIds[j] != selectedChrId){
				var chrId = selectedEntryPointsIds[j];
				var chrUrl =  YAHOO.dasBrowser.genome.karyotypeStructure.proxyUrl + "?" + YAHOO.dasBrowser.proxy.parameters.source + "=" + YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomes[chrId].url;
				var request = YAHOO.util.Connect.asyncRequest('GET', chrUrl, ensemblKaryotypeBandsCallback);
				YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.mappingRequestIdChromosomeId[request.tId]=chrId;
			}
		}
	}
}

/*
 * Annotation request
 */
YAHOO.dasBrowser.genome.request.makeAnnotationRequest = function(){
	var selectedChromosome = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.selectedChromosome;
	var karyotypeMaxbins = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.annotationLimit;
	var chromosomeMaxbins = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.annotationLimit;
	var bandMaxbins = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.bandConf.annotationLimit;
	var zoomMaxbins = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.zoomConf.annotationLimit; 
	
	var selectedEntryPoints = YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.selectedEntryPoints;
	var annotationSources = YAHOO.dasBrowser.genome.annotations.sources;
	var countTopSources = 0;
	var countBottomSources = 0;
	
	var annotationColors = YAHOO.dasBrowser.genome.annotations.simpleView.annotationColors;
	var annotationColorControl = 0;
	var annotationColorControlTemp = 0;
			
	for (var j = 0; j < annotationSources.length; j++) {
		// Set color
		var selectedAnnotationColor = annotationColors[annotationColorControl];
		annotationColorControlTemp = annotationColorControl;
		if(annotationColors.length-1 > annotationColorControlTemp){
			annotationColorControl++;
		} else {
			annotationColorControl = 0;
		}
		annotationSources[j].color = selectedAnnotationColor;


		//Set annotation types prefix
		var annotationTypesSelected = YAHOO.dasBrowser.genome.annotations.sources[j].types;
		var annotationTypesSufix = "";
		if(annotationTypesSelected.length > 0){
			for (var k = 0; k < annotationTypesSelected.length; k++) {
				annotationTypesSufix = annotationTypesSufix + ";type=" + annotationTypesSelected[k];
			}
		}

		// Set annotation container position
		if(annotationSources[j].representation == "line" || annotationSources[j].representation == "chart"){
			countBottomSources++;
			annotationSources[j].align = "top";
			annotationSources[j].position = countBottomSources;
		} else {
			countTopSources++;
			annotationSources[j].align = "bottom";
			annotationSources[j].position = countTopSources;
		}

		
		// Set Request
		YAHOO.dasBrowser.genome.annotations.sources[j].result = new Array();
		//YAHOO.dasBrowser.genome.annotations.sources[j].segment = new Array();
		YAHOO.dasBrowser.genome.annotations.sources[j].arrayPosition = j;
		YAHOO.dasBrowser.genome.annotations.sources[j].highestScore = null;
		YAHOO.dasBrowser.genome.annotations.sources[j].lowestScore = null;
		YAHOO.dasBrowser.genome.annotations.sources[j].segmentCount = 0;
		//YAHOO.dasBrowser.genome.annotations.sources[j].segmentRequests = 0;
		YAHOO.dasBrowser.genome.annotations.sources[j].loadCompleted = false;
		YAHOO.dasBrowser.genome.annotations.sources[j].cvLoaded = false;
		var sourceUrl = annotationSources[j].url + "?segment=";
		for (var i = 0; i < selectedEntryPoints.ids.length; i++) {
			if(YAHOO.lang.isUndefined(YAHOO.dasBrowser.genome.annotations.sources[j].result[selectedEntryPoints.ids[i]])){
				YAHOO.dasBrowser.genome.annotations.sources[j].result[selectedEntryPoints.ids[i]] = new myAnnotationResult();
			}
			var segmentId = YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.allEntryPoints[selectedEntryPoints.ids[i]].id;
			var segmentStart = YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.allEntryPoints[selectedEntryPoints.ids[i]].start;
			var segmentStop = YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.allEntryPoints[selectedEntryPoints.ids[i]].stop;
			if (YAHOO.dasBrowser.genome.annotations.sources[j].panel == "karyotype") {
				//console.log(selectedEntryPoints.ids[i]);
				var annotationUrl = YAHOO.dasBrowser.genome.karyotypeStructure.proxyUrl + "?" + YAHOO.dasBrowser.proxy.parameters.source + "=" + escape(sourceUrl + segmentId + ":" + segmentStart + "," + segmentStop + ";maxbins=" + karyotypeMaxbins + annotationTypesSufix);
				var request = YAHOO.util.Connect.asyncRequest('GET', annotationUrl, annotationCallback);
				YAHOO.dasBrowser.genome.annotations.mappingRequestIdSource[request.tId] = new Object;
				YAHOO.dasBrowser.genome.annotations.mappingRequestIdSource[request.tId].source = [j];
				YAHOO.dasBrowser.genome.annotations.mappingRequestIdSource[request.tId].chromosome = selectedEntryPoints.ids[i];
				YAHOO.dasBrowser.genome.annotations.mappingRequestIdSource[request.tId].view = "Kv";
				YAHOO.dasBrowser.genome.annotations.mappingRequestIdSource[request.tId].redraw = false;
			} else {
				//YAHOO.dasBrowser.genome.annotations.sources[j].segmentCount++;
				//console.log(YAHOO.dasBrowser.genome.annotations.sources[j].segmentCount);
			}
			if(YAHOO.dasBrowser.genome.annotations.sources[j].panel == "karyotype" || YAHOO.dasBrowser.genome.annotations.sources[j].panel == "chromosome"){
				if (selectedChromosome == selectedEntryPoints.ids[i]) {
					var annotationUrl = YAHOO.dasBrowser.genome.karyotypeStructure.proxyUrl + "?" + YAHOO.dasBrowser.proxy.parameters.source + "=" + escape(sourceUrl + segmentId + ":" + segmentStart + "," + segmentStop + ";maxbins=" + chromosomeMaxbins + annotationTypesSufix);
					var request = YAHOO.util.Connect.asyncRequest('GET', annotationUrl, annotationCallback);
					YAHOO.dasBrowser.genome.annotations.mappingRequestIdSource[request.tId] = new Object;
					YAHOO.dasBrowser.genome.annotations.mappingRequestIdSource[request.tId].source = [j];
					YAHOO.dasBrowser.genome.annotations.mappingRequestIdSource[request.tId].chromosome = selectedEntryPoints.ids[i];
					YAHOO.dasBrowser.genome.annotations.mappingRequestIdSource[request.tId].view = "Cv";
					YAHOO.dasBrowser.genome.annotations.mappingRequestIdSource[request.tId].redraw = false;
				}
						
				/* 
				var selectedBand = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.bandConf.selectedBand;
				var selectedBandIdStart = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomes[selectedChromosome].bands[selectedBand].start;
				var selectedBandIdEnd = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomes[selectedChromosome].bands[selectedBand].end;
				console.log("star: " + selectedBandIdStart + ", end: " + selectedBandIdEnd);
				var annotationUrl = YAHOO.dasBrowser.genome.karyotypeStructure.proxyUrl + "?" + YAHOO.dasBrowser.proxy.parameters.source + "=" + sourceUrl + segmentId + ":" + selectedBandIdStart + "," + selectedBandIdEnd + ";maxbins=" + bandMaxbins + annotationTypesSufix;
				var request = YAHOO.util.Connect.asyncRequest('GET', annotationUrl, annotationCallback);
				YAHOO.dasBrowser.genome.annotations.mappingRequestIdSource[request.tId] = new Object;
				YAHOO.dasBrowser.genome.annotations.mappingRequestIdSource[request.tId].source = [j];
				YAHOO.dasBrowser.genome.annotations.mappingRequestIdSource[request.tId].chromosome = selectedEntryPoints.ids[i];
				YAHOO.dasBrowser.genome.annotations.mappingRequestIdSource[request.tId].view = "Bv";
				*/
			}
		}
	}
}

/*
 * Sequence request
 */
YAHOO.dasBrowser.genome.request.makeSequenceRequest = function(selectedChromosome, selectedSequenceStart, selectedSequenceEnd){	
	var segmentId = YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.allEntryPoints[selectedChromosome].id;
	var url = YAHOO.dasBrowser.genome.karyotypeStructure.proxyUrl + "?" + YAHOO.dasBrowser.proxy.parameters.source + "=http://www.ensembl.org/das/Homo_sapiens.GRCh37.reference/sequence?segment=" + segmentId + ':'+selectedSequenceStart+','+selectedSequenceEnd;
	var request = YAHOO.util.Connect.asyncRequest('GET', url, ensemblSequenceCallback);
}

/*
 * Ensembl Sequence Callback
 */
var ensemblSequenceCallback = {
	timeout: 10000,
    success:function(o){
        var ensemblSequenceResults = YAHOO.dasBrowser.genome.karyotypeStructure.sequence.parse(o.responseXML);
        YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.sequenceConf.sequenceObject = ensemblSequenceResults;
		YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.drawSequence(ensemblSequenceResults);
    },
    failure:function(o){
        //console.log("failure: ensembl sequence request");
    }
};

/*
 * Source stylesheet Callback
 */
var sourceStylesheetCallback = {
	timeout: 10000,
    success:function(o){
		var sourceNumber = YAHOO.dasBrowser.genome.annotations.mappingRequestIdAnnotationSource[o.tId];
		//console.log(sourceNumber);
		var stylesheetData = YAHOO.dasBrowser.genome.annotations.sources[sourceNumber].stylesheetData;
		stylesheetData.types = new Object();
        var sourceStylesheetResults = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.stylesheet.parse(o.responseXML);
        stylesheetData.types = sourceStylesheetResults.allKaryotypeStylesheetTypes;
    },
    failure:function(o){
		var sourceNumber = YAHOO.dasBrowser.genome.annotations.mappingRequestIdAnnotationSource[o.tId];
		YAHOO.dasBrowser.genome.annotations.sources[sourceNumber].stylesheet = false;
        //console.log("failure: stylesheet request, " + YAHOO.dasBrowser.genome.annotations.sources[sourceNumber].name);
    }
};


/*
 * Ensembl DSN Callback
 */
var ensemblDsnCallback = {
	timeout: 10000,
    success:function(o){
        var ensemblDsnResults = YAHOO.dasBrowser.genome.karyotypeStructure.dsn.parseEnsemblDsn(o.responseXML, YAHOO.dasBrowser.genome.karyotypeStructure.dsn.selectedDsn.id);
		if(ensemblDsnResults.allEnsemblDsn.length == 0){
			YAHOO.example.container.wait.setHeader("DSN request failure ...");
    		YAHOO.example.container.wait.setBody("This software was not able to access the DSN of Ensembl to create the karyotype structure view. We recomend you to try again or come back in few minutes. If the problem persist please contact the <a href=\"http://www.ensembl.org/info/about/contact/index.html\" target=\"_blank\">Ensembl Helpdesk</a>");
        	//console.log("failure: ensemblDsn request empty");
		} else {
			YAHOO.dasBrowser.genome.karyotypeStructure.dsn.allDsn = ensemblDsnResults.allEnsemblDsn;
			YAHOO.dasBrowser.genome.karyotypeStructure.dsn.selectedDsn.referenceLocation = ensemblDsnResults.referenceLocation;
			YAHOO.dasBrowser.genome.karyotypeStructure.dsn.selectedDsn.karyotypeLocation = ensemblDsnResults.karyotypeLocation;
			//console.log(ensemblDsnResults.karyotypeLocation);
			YAHOO.dasBrowser.genome.request.makeEnsemblEntryPointsRequest();
			if (YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.stylesheet.useCustomStylesheet) {
				YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.stylesheet.setCustomValuesAndColors();
			} else {
				YAHOO.dasBrowser.genome.request.makeEnsemblKaryotypeStylesheetRequest();
			}
		}
    },
    failure:function(o){
		YAHOO.example.container.wait.setHeader("DSN request failure ...");
    	YAHOO.example.container.wait.setBody("This software was not able to access the DSN of Ensembl to create the karyotype structure view. We recomend you to try again or come back in few minutes. If the problem persist please contact the <a href=\"http://www.ensembl.org/info/about/contact/index.html\" target=\"_blank\">Ensembl Helpdesk</a>");
        //console.log("failure: ensemblDsn request");
    }
};


/*
 * Ensembl Entry Point Callback
 */
var ensemblEntryPointsCallback = {
	timeout: 10000,
    success:function(o){
		/*
		* Parse entry Points
        */
        var ensemblEntryPointsResults = YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.parseEnsemblEntryPoints(o.responseXML, YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.selectedEntryPoints.type);
		YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.allEntryPoints = ensemblEntryPointsResults.allEnsemblEntryPoints;
		YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.ids = ensemblEntryPointsResults.ids;
		
		if(ensemblEntryPointsResults.ids.length == 0){
			YAHOO.example.container.wait.setHeader("Entry Points request failure ...");
    		YAHOO.example.container.wait.setBody("This software was not able to access the Entry Points of Ensembl to create the karyotype structure view. We recomend you to try again or come back in few minutes. If the problem persist please contact the <a href=\"http://www.ensembl.org/info/about/contact/index.html\" target=\"_blank\">Ensembl Helpdesk</a>");
        	//console.log("failure: ensembl Entry Point request empty");
		} else {
			
			/*
			* Select just user entry Points defined by the user
	        */
			if(YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.userEntryPoints.length >0){
				var userEntryPoints = YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.userEntryPoints;
				var newUserEntryPoints = new Array();
				for (var j = 0; j < userEntryPoints.length; j++) {
					newUserEntryPoints.push(YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.selectedEntryPoints.type + userEntryPoints[j]);
				}
				YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.selectedEntryPoints.ids = newUserEntryPoints;	
			} else {
				YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.selectedEntryPoints.ids = ensemblEntryPointsResults.ids;
			}
			var selectedEntryPoints = YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.selectedEntryPoints;
	        
			/*
			* Select one chromosome for the chromosome view
	        */
			var selectedChromosome = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.selectedChromosome;
			if(selectedChromosome == null)
				{
				 YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.selectedChromosome = selectedEntryPoints.ids[0]; // Default
				}
			selectedChromosome = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.selectedChromosome;
			
			/*
			* Create chromosome object
	        */
			//YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.createChromosomeObjects(selectedEntryPoints.ids);
			YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.createChromosomeObjects(ensemblEntryPointsResults.ids);
	
			/*
			* Set chromosomes Px legth
	        */
			var allChrLength = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.mappingChrIdChrLength;
			var longestChromosome = YAHOO.dasBrowser.util.findKeyForBiggestValueOnAssocArray(allChrLength);
			YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.longestChromosome = longestChromosome;
			var chromosomeProportion = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.chromosomeWidthPx/YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.allEntryPoints[longestChromosome].length;
			YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.chromosomeProportion = chromosomeProportion;
			YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.setMappingChrIdChrWidhtPx(allChrLength,chromosomeProportion);
			
			/*
			* Check if this specie has a karyotype source
	        */
			var isNullKaryotypeFeatures = YAHOO.lang.isNull(YAHOO.dasBrowser.genome.karyotypeStructure.dsn.selectedDsn.karyotypeLocation);
			
			/*
			* Sort Entry points to display them in order on the karyotype view
	        */
			YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.sortSelectedEntryPoints(
				selectedEntryPoints.ids,
				selectedEntryPoints.type
			);
	
			/*
			* Calculate the number of sources to display
	        */
			var chromosomeBandDrawRequestNumber = calculateChromosomeBandDrawRequestNumber();
			YAHOO.dasBrowser.genome.request.drawing.chromosomeBands.total = chromosomeBandDrawRequestNumber;
			//console.log("B"+chromosomeBandDrawRequestNumber);
					
			var annotationDrawRequestNumber = calculateAnnotationDrawRequestNumber();
			YAHOO.dasBrowser.genome.request.drawing.annotations.total = annotationDrawRequestNumber;
			//console.log("A"+annotationDrawRequestNumber);
					
			YAHOO.dasBrowser.genome.request.drawing.isCompleted();
			
			/*
			* ON KARYOTYPE VIEW -> CREATE LAYOUT 
	        */		
			YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.drawKaryotypeViewStructure(
				selectedEntryPoints.ids,
				YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.layout
			);
			for (var j = 0; j < selectedEntryPoints.ids.length; j++) {
				YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.addRedrawChromosomeListener(selectedEntryPoints.ids[j]);
			}
			
			/*
			* ON CHROMOSOME VIEW -> CREATE LAYOUT 
	        */	
			YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.drawChromosomeViewStructure(
				YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.selectedChromosome,
				YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.layout
			);
	
			
			/*
			* ON CHROMOSOME VIEW -> DRAW SLIDER 
	        */	
			var pxWidth = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.chromosomeWidthPx;
			var chromosomeSlider = new mySlider("CvSliderFrame_" + YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.selectedChromosome, "CvSlider_" + YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.selectedChromosome);
			chromosomeSlider.setHtml();
			chromosomeSlider.setRange(pxWidth);
			chromosomeSlider.setBgImg("img/bg-slider.png", pxWidth+"px");
			chromosomeSlider.setSeqStart(parseInt(YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.allEntryPoints[selectedChromosome].start));
			chromosomeSlider.setSeqStop(parseInt(YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.allEntryPoints[selectedChromosome].stop));
			chromosomeSlider.setSlider();
	
			/*
			* ON CHROMOSOME VIEW -> DRAW CHROMOSOME
	        */				
			YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.drawChromosome(
				YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.selectedChromosome,
				YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.labelPrefix,
				YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.chromosomeWidthPx,
				YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.chromosomeHeightPx
			);
	
			/*
			* ON KARYOTYPE VIEW -> DRAW CHROMOSOMES
	        */			
	
			for (var j = 0; j < selectedEntryPoints.ids.length; j++) {
				YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.drawChromosome(
					selectedEntryPoints.ids[j],
					YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.labelPrefix,
					YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.mappingChrIdChrWidhtPx[selectedEntryPoints.ids[j]],
					YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.chromosomeHeightPx
				);
			}
	
			/*
			* FOR CHROMOSOME VIEW -> CHROMOSOME-BAND REQUEST
	        */			
			if(isNullKaryotypeFeatures == false){
					YAHOO.dasBrowser.genome.request.makeEnsemblChromosomeBandsRequest();
			}
		
			
			/*
			* FOR KARYOTYPE AND CHROMOSOME VIEW -> ANNOTATION REQUEST
	        */
			YAHOO.dasBrowser.genome.request.makeAnnotationRequest();
			
			
			/*
			* ADD external Sources
			*/
			if(sessvars){
				if(sessvars.karyoDas){
					if(sessvars.karyoDas.conf.decipher.patient){
						if(sessvars.karyoDas.conf.decipher.patient.source.annotations){
							//var url = YAHOO.dasBrowser.genome.karyotypeStructure.proxyUrl + "?" + YAHOO.dasBrowser.proxy.parameters.source + "=" + stylesheetUrl;			
							var url = "decipher_stylesheet.xml";
							var request = YAHOO.util.Connect.asyncRequest('GET', url, externalSourceStylesheetCallback);
						}
					}
				}
			}
			//YAHOO.dasBrowser.genome.annotations.sources.push(Dsource);
			// create features, use function similar to annotation callback.
		
		}
    },
    failure:function(o){
        //console.log("failure: EntryPoints request");
		YAHOO.example.container.wait.setHeader("Ensembl request failure ...");
    	YAHOO.example.container.wait.setBody("This software was not able to access the Entry Points of Ensembl to create the karyotype structure view. We recomend you to try again or come back in few minutes. If the problem persist please contact the <a href=\"http://www.ensembl.org/info/about/contact/index.html\" target=\"_blank\">Ensembl Helpdesk</a>");
    }
};

/*
 * Ensembl Karyotype Stylesheet Callback
 */
var ensemblKaryotypeStylesheetCallback = {
	timeout: 10000,
    success:function(o){
		var stylesheet = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.stylesheet;
		var ensemblKaryotypeStylesheetResults = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.stylesheet.parse(o.responseXML);
		stylesheet.allTypes = ensemblKaryotypeStylesheetResults.allKaryotypeStylesheetTypes;
		stylesheet.valuesAndColors = stylesheet.setStylesheetValuesAndColors(stylesheet.allTypes);
    },
    failure:function(o){
        //console.log("failure: Karyotype Stylesheet request");
    }
};


/*
 * Ensembl Chromosome Bands Callback
 */
var ensemblChromosomeBandsCallback = {
	//timeout: 10000,
    success:function(o){
		var chrId = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.selectedChromosome;
		if(o.responseXML == null){
			//console.log(chrId);
		}
		var chromosomeBandsResults = YAHOO.dasBrowser.genome.annotationSources.parseAnnotationFeatures(o.responseXML);
		if(chromosomeBandsResults.allfeatures.length > 0){
			YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomes[chrId].bands = chromosomeBandsResults.allfeatures;
			var isNullKaryotypeFeatures = YAHOO.lang.isNull(YAHOO.dasBrowser.genome.karyotypeStructure.dsn.selectedDsn.karyotypeLocation);
			if(isNullKaryotypeFeatures == false){
				//ON CHROMOSOME VIEW -> DRAW CHROMOSOMES-BANDS
				YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.drawChromosomeBands(
					chrId,
					YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.labelPrefix,
					YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.chromosomeWidthPx,
					YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.chromosomeHeightPx
				);
				//ON KARYOTYPE VIEW -> DRAW CHROMOSOMES-BANDS
				YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.drawChromosomeBands(
					chrId,
					YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.labelPrefix,
					YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.mappingChrIdChrWidhtPx[chrId],
					YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.chromosomeHeightPx
				);
			}
			YAHOO.dasBrowser.genome.request.drawing.chromosomeBands.completed++;
			YAHOO.dasBrowser.genome.request.drawing.isCompleted();
			
			//FOR KARYOTYPE VIEW -> CHROMOSOME-BAND REQUEST
			YAHOO.dasBrowser.genome.request.makeEnsemblKaryotypeRequest();
		}
	},
    failure:function(o){
        //console.log("failure: Chromosome bands request");
		YAHOO.dasBrowser.genome.request.drawing.chromosomeBands.completed++;
		YAHOO.dasBrowser.genome.request.drawing.isCompleted();
    }
};



/*
 * Ensembl Karyotype Bands Callback
 */
var ensemblKaryotypeBandsEvents = {
	start:function(type, args){
		//console.log("start3:");
	},
	complete:function(){
		//console.log("complete3:");
	}
}
var ensemblKaryotypeBandsCallback = {
	//timeout: 30000,
	customevents:{ 
		onStart:ensemblKaryotypeBandsEvents.start,
		onComplete:ensemblKaryotypeBandsEvents.complete
	},
	start:function(o){
		//console.log("complete:" + YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.mappingRequestIdChromosomeId[o.tId]);
	},
	complete:function(o){
		//console.log("complete:" + YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.mappingRequestIdChromosomeId[o.tId]);
	},
    success:function(o){
		//console.log("success:" + YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.mappingRequestIdChromosomeId[o.tId]);
		var chrId = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.mappingRequestIdChromosomeId[o.tId];
		if(o.responseXML == null){
			//console.log(chrId);
		}
		var chromosomeBandsResults = YAHOO.dasBrowser.genome.annotationSources.parseAnnotationFeatures(o.responseXML);
		//console.log('ensemblKaryotypeBandsCallback'+o.tId);
		if (chromosomeBandsResults.allfeatures.length > 0) {
			YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomes[chrId].bands = chromosomeBandsResults.allfeatures;
			var selectedBand = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.bandConf.selectedBand;
			var isNullKaryotypeFeatures = YAHOO.lang.isNull(YAHOO.dasBrowser.genome.karyotypeStructure.dsn.selectedDsn.karyotypeLocation);
			if(isNullKaryotypeFeatures == false){
				//ON KARYOTYPE VIEW -> DRAW CHROMOSOME-BAND
				YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.drawChromosomeBands(
					chrId,
					YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.labelPrefix,
					YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.mappingChrIdChrWidhtPx[chrId],
					YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.chromosomeHeightPx
				);
				//YAHOO.dasBrowser.genome.request.drawing.chromosomeBands.completed++;
				//console.log("B"+YAHOO.dasBrowser.genome.request.drawing.chromosomeBands.completed);
			}
		}
		YAHOO.dasBrowser.genome.request.drawing.chromosomeBands.completed++;
		YAHOO.dasBrowser.genome.request.drawing.isCompleted();
    },
    failure:function(o){
        //console.log("failure: Karyotype bands request");
		YAHOO.dasBrowser.genome.request.drawing.chromosomeBands.completed++;
		YAHOO.dasBrowser.genome.request.drawing.isCompleted();
    }
};


/*
 * Annotation Callback
 */
var annotationCallback = {
	//timeout: 20000,
    success:function(o){
		/*
		* Parse annotation results for one source
        */
		if(o.responseXML == null){
			//console.log(YAHOO.dasBrowser.genome.annotations.mappingRequestIdSource[o.tId].chromosome);
		}
		var annotationResults = YAHOO.dasBrowser.genome.annotationSources.parseAnnotationFeatures(o.responseXML);
		var sourceArrayNumber = YAHOO.dasBrowser.genome.annotations.mappingRequestIdSource[o.tId].source;
		var chrId = YAHOO.dasBrowser.genome.annotations.mappingRequestIdSource[o.tId].chromosome;
		var viewType = YAHOO.dasBrowser.genome.annotations.mappingRequestIdSource[o.tId].view;
		var redraw = YAHOO.dasBrowser.genome.annotations.mappingRequestIdSource[o.tId].redraw;
		var annotationSource = YAHOO.dasBrowser.genome.annotations.sources[sourceArrayNumber];
		var positionalFeatures = 0;

		
		/*
		* Add to the count Karyotype sources
        */
		if (viewType == "Kv") {
			annotationSource.segmentCount++;
		}	
		
		if (annotationResults.allfeatures.length == 0) {
			/*
			 * Check empty results
			 */
			YAHOO.dasBrowser.genome.annotations.segmentSourcesFailed++;
			//annotationSource.segment[chrId] = null;
		} //else {

			/*
			* Add annotation to the annotation results Object and Set variables per view
        	*/
			if(viewType == "Kv"){
				annotationSource.result[chrId].setKvFeatures(annotationResults.allfeatures);
				annotationSource.result[chrId].setKvSegment(annotationResults.segment);
				var features = annotationSource.result[chrId].kv.features;
				var segment = annotationSource.result[chrId].kv.segment;
				//console.log(segment);
				var labelPrefix = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.karyotypeConf.labelPrefix;
			} else if(viewType == "Cv"){
				annotationSource.result[chrId].setCvFeatures(annotationResults.allfeatures);
				annotationSource.result[chrId].setCvSegment(annotationResults.segment);
				annotationSource.result[chrId].setHigherDefinitionView(viewType);
				var features = annotationSource.result[chrId].cv.features;
				var segment = annotationSource.result[chrId].cv.segment;
				var labelPrefix = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.labelPrefix;	
			} else if(viewType == "Zv"){
				annotationSource.result[chrId].setZvFeatures(annotationResults.allfeatures);
				annotationSource.result[chrId].setZvSegment(annotationResults.segment);
				annotationSource.result[chrId].setHigherDefinitionView(viewType);
				var features = annotationSource.result[chrId].zv.features;
				var segment = annotationSource.result[chrId].zv.segment;
				var labelPrefix = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.zoomConf.labelPrefix;
			} else if (viewType == "Bv") {
				annotationSource.result[chrId].setBvFeatures(annotationResults.allfeatures);
				annotationSource.result[chrId].setBvSegment(annotationResults.segment);
				annotationSource.result[chrId].setHigherDefinitionView(viewType);
				var features = annotationSource.result[chrId].bv.features;
				var segment = annotationSource.result[chrId].bv.segment;
				var labelPrefix = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.bandConf.labelPrefix;
			} else {
				//console.log("Warning ... no viewType defined on Karyotype Request");		
			}
			
			/*
			* Find out source Highest Score 
        	*/
			if (annotationResults.segment != null) {
				if (annotationResults.segment.highestScore != null) {
					var sourceHighestScoreTemp = annotationSource.highestScore;
					if (sourceHighestScoreTemp == null) {
						annotationSource.highestScore = annotationResults.segment.highestScore;
					}
					else {
						if (annotationResults.segment.highestScore > sourceHighestScoreTemp) {
							annotationSource.highestScore = annotationResults.segment.highestScore;
						}
					}
				}
			}
			
			/*
			* Find out source Lowest Score 
        	*/
			if (annotationResults.segment != null) {
				if (annotationResults.segment.lowestScore != null) {
					var sourceLowestScoreTemp = annotationSource.lowestScore;
					if (sourceLowestScoreTemp == null) {
						annotationSource.lowestScore = annotationResults.segment.lowestScore;
					}
					else {
						if (annotationResults.segment.lowestScore < sourceLowestScoreTemp) {
							annotationSource.lowestScore = annotationResults.segment.lowestScore;
						}
					}
				}
			}


			/*
			* Draw annotations
			*/
			if (annotationSource.representation == 'mark' || annotationSource.representation == 'track') {
				/*
				* Draw features by segment asyncronously
        		*/
				positionalFeatures = 0;
				if (annotationResults.segment != null) {
					YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.drawAnnotations(features, segment, null, chrId, labelPrefix, sourceArrayNumber);
					positionalFeatures = segment.positional;
				}
				//console.log("g:"+positionalFeatures);
				YAHOO.dasBrowser.genome.annotations.simpleView.drawLegend(labelPrefix, chrId, sourceArrayNumber, positionalFeatures);					
				YAHOO.dasBrowser.genome.request.drawing.annotations.completed++;
			} else {
				/*
				* Draw features in a redraw request for line and chart representations
        		*/
				if(redraw == true){
					//if (viewType == "Cv" && annotationSource.loadCompleted) {
					if (viewType == "Cv") {
						//setTimeout('YAHOO.dasBrowser.genome.request.ajaxRequestControl(\'' + "annotation" + '\',\'' + "success" + '\',' + sourceArrayNumber + ',\'' + chrId + '\',\'' + "Cv" + '\')', 0);
						annotationSource.cvLoaded = true;
					}
					if (viewType != "Kv") {
						//setTimeout('YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.drawAnnotations(\'' + features + ',\'' + segment + '\',\'' + "null" + ',\'' + chrId + ',\'' + labelPrefix + ',\'' + sourceArrayNumber + '\')', 0);
						YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.drawAnnotations(features, segment, null, chrId, labelPrefix, sourceArrayNumber);
						//console.log("h:"+segment.positional);
						YAHOO.dasBrowser.genome.annotations.simpleView.drawLegend(labelPrefix, chrId, sourceArrayNumber, segment.positional);
						YAHOO.dasBrowser.genome.request.drawing.annotations.completed++;
					}
				}
				
				/*
				* Draw features on the chromosome view for line and chart representations
        		*/

				if(annotationSource.panel == "chromosome" && viewType == "Cv" && redraw == false){
					YAHOO.dasBrowser.genome.annotations.setScores(sourceArrayNumber);
					var selectedChromosome = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.selectedChromosome;
					//setTimeout('YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.drawAnnotations(\'' + features + ',\'' + segment + '\',\'' + "null" + ',\'' + selectedChromosome + ',\'' + labelPrefix + ',\'' + sourceArrayNumber + '\')', 0);
					features = annotationSource.result[selectedChromosome].cv.features;
					segment = annotationSource.result[selectedChromosome].cv.segment;
					YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.drawAnnotations(features, segment, "null", selectedChromosome, labelPrefix, sourceArrayNumber);
					//console.log("i"+segment.positional);
					YAHOO.dasBrowser.genome.annotations.simpleView.drawLegend(labelPrefix, selectedChromosome, sourceArrayNumber, segment.positional);
					YAHOO.dasBrowser.genome.request.drawing.annotations.completed++;
				}
				
				/*
				* Draw features on the karyotype view for line and chart representations
        		*/
				if(viewType == "Kv") {
				// Draw features just once all the features for all the segments have been loaded. Compulsory since the client needs to calculate the highest and lowest score.
					var selectedEntryPoints = YAHOO.dasBrowser.genome.karyotypeStructure.entryPoints.selectedEntryPoints;
					if (annotationSource.segmentCount == selectedEntryPoints.ids.length) {
						annotationSource.loadCompleted = true;
						YAHOO.dasBrowser.genome.annotations.setScores(sourceArrayNumber);
						
						if(annotationSource.cvLoaded == false){
							//CHROMOSOME
							var selectedChromosome = YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.chromosomeConf.selectedChromosome;
							features = annotationSource.result[selectedChromosome].kv.features;
							segment = annotationSource.result[selectedChromosome].kv.segment;
							var positionalFeatures = 0;
							if(segment != null){
								YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.drawAnnotations(features, segment, null, selectedChromosome, "Cv", sourceArrayNumber);								
								positionalFeatures = segment.positional;
							}
							//console.log("j"+positionalFeatures);
							YAHOO.dasBrowser.genome.annotations.simpleView.drawLegend("Cv", selectedChromosome, sourceArrayNumber, positionalFeatures);
							YAHOO.dasBrowser.genome.request.drawing.annotations.completed++;
							
						}
						//KARYOTYPE
						for (var i = 0; i < selectedEntryPoints.ids.length; i++) {
							//setTimeout('YAHOO.dasBrowser.genome.request.ajaxRequestControl(\'' + "annotation" + '\',\'' + "success" + '\',' + sourceArrayNumber + ',\'' + selectedEntryPoints.ids[i] + '\',\'' + "Kv" + '\')', 0);
							features = annotationSource.result[selectedEntryPoints.ids[i]].kv.features;
							segment = annotationSource.result[selectedEntryPoints.ids[i]].kv.segment;
							var positionalFeatures = 0;
							if(segment != null){
								YAHOO.dasBrowser.genome.karyotypeStructure.karyotype.drawAnnotations(features, segment, null, selectedEntryPoints.ids[i], labelPrefix, sourceArrayNumber);
								positionalFeatures = segment.positional;
							}
							//console.log("j"+positionalFeatures);
							YAHOO.dasBrowser.genome.annotations.simpleView.drawLegend(labelPrefix, selectedEntryPoints.ids[i], sourceArrayNumber, positionalFeatures);
							YAHOO.dasBrowser.genome.request.drawing.annotations.completed++;
						}
					}		
				}
			}
		//}
		YAHOO.dasBrowser.genome.request.drawing.isCompleted();
		//}
    },
    failure:function(o){
        //console.log("failure: Chromosome bands request");
    }
};


YAHOO.dasBrowser.genome.annotations.setScores = function(sourceArrayNumber){
	var annotationSource = YAHOO.dasBrowser.genome.annotations.sources[sourceArrayNumber]
	var lowestScore = annotationSource.lowestScore;
	var highestScore = annotationSource.highestScore;
	if (lowestScore == highestScore) {
		if (lowestScore == 0) {
			annotationSource.lowestScore = -1;
		} else {
			annotationSource.lowestScore = lowestScore - highestScore;
		}
	} else {
		annotationSource.lowestScore = lowestScore - (highestScore - lowestScore);
	}
	//console.log(annotationSource.highestScore);
	//console.log(annotationSource.lowestScore);
	//console.log(lowestScore);
}


